package com.kit.data.kitopeso.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.exifinterface.media.ExifInterface;


import com.kit.data.kitopeso.R;
import com.kit.data.kitopeso.base.BaseActivity;
import com.kit.data.kitopeso.databinding.KitoSefieCameraActivityBinding;
import com.kit.data.kitopeso.net.PU;
import com.kit.data.kitopeso.net.RxHttp;
import com.kit.data.kitopeso.net.U;
import com.kit.data.kitopeso.tools.BarUtils;
import com.kit.data.kitopeso.tools.Camera2Helper;
import com.kit.data.kitopeso.tools.FileUtils;
import com.kit.data.kitopeso.tools.JsonParse;
import com.kit.data.kitopeso.tools.LogUtil;
import com.kit.data.kitopeso.tools.ResUtils;
import com.kit.data.kitopeso.tools.ViewUtils;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.PictureResult;
import com.otaliastudios.cameraview.VideoResult;
import com.otaliastudios.cameraview.controls.Mode;
import com.otaliastudios.cameraview.gesture.Gesture;
import com.otaliastudios.cameraview.gesture.GestureAction;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class KitoSefieCameraActivity extends BaseActivity<KitoSefieCameraActivityBinding> {

    private final int MY_PERMISSIONS_CAMERA = 1;

    Camera2Helper camera2Helper;


    String mUrl;

    File photoFile;

    @Override
    protected KitoSefieCameraActivityBinding initViewBinding(LayoutInflater inflater) {
        return KitoSefieCameraActivityBinding.inflate(inflater);
    }



    @Override
    protected void initView() {
        BarUtils.showLightStatusBars(getActivity(), false);
        binding.getRoot().setPadding(0, 0, 0, 0);
        setStatusBarHeight(binding.tvRoot);
        binding.tvBk.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            finish();
        });
        binding.tvBtn.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            PU.userBuriedPoint(PU.P151, "");
            photoFile = FileUtils.createImageFile(getActivity());
            if (photoFile != null && camera2Helper != null) {
                LogUtil.e("me", "camera2Helper->" + camera2Helper);
                camera2Helper.takePicture();
                switchState(1);
            } else {
                initCamera();
            }
        });
        binding.tvRefresh.setOnClickListener(view -> {
            ViewUtils.viewScale(view);
            PU.userBuriedPoint(PU.P152, "");
            switchState(0);
        });
        binding.tvBtn1.setOnClickListener(view -> {
            ViewUtils.viewScale(view);
            PU.userBuriedPoint(PU.P153, "");
            if (!TextUtils.isEmpty(mUrl)) {
                Intent intent = new Intent();
                intent.putExtra("url", mUrl);
                setResult(RESULT_OK, intent);
                finish();
            } else {
                showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.upload_failed));
            }
        });

        binding.camera.setLifecycleOwner(this);
        binding.camera.addCameraListener(new CameraListener() {
            @Override
            public void onPictureTaken(@NonNull PictureResult result) {
                // A Picture was taken!
                saveImg(result.getData(), result.getRotation());
                camera2Helper.closeCamera();
            }

            @Override
            public void onVideoTaken(@NonNull VideoResult result) {
                // A Video was taken!
            }

            // And much more
        });

        binding.camera.setMode(Mode.PICTURE);
        binding.camera.mapGesture(Gesture.PINCH, GestureAction.ZOOM);
        binding.camera.setAudio(null);

        camera2Helper = new Camera2Helper(binding.camera);

        initCamera();


    }

    @Override
    protected void onRestart() {
        super.onRestart();
        initCamera();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (camera2Helper != null) {
            camera2Helper.closeCamera();
        }
    }

    @Override
    protected void initData() {
        UP_TYPE1 = PU.P148;
        UP_TYPE2 = PU.P149;
    }

    void switchState(int i) {
        if (i == 0) {
            binding.tvRefreshLayout.setVisibility(View.GONE);
            binding.tvBtn.setVisibility(View.VISIBLE);
            camera2Helper.openCamera(false);
            camera2Helper.startPreview();
            mUrl = "";
            photoFile = null;
        } else {
            binding.tvRefreshLayout.setVisibility(View.VISIBLE);
            binding.tvBtn.setVisibility(View.INVISIBLE);
        }
    }

    void saveImg(byte[] bytes, int myorientation) {
        if (photoFile != null) {

            Observable<String> observable = Observable.create(emitter -> {
                try (FileOutputStream fos = new FileOutputStream(photoFile)) {
                    fos.write(bytes);
                    ExifInterface exif = new ExifInterface(photoFile.getAbsolutePath());
//                    exif.setAttribute(ExifInterface.TAG_ORIENTATION, String.valueOf(myorientation));
                    exif.saveAttributes();
                    fos.flush();
                } catch (IOException e) {
                    LogUtil.e("me", "saveImage->" + e);
                } finally {
                    emitter.onNext("");
                    emitter.onComplete();
                }

            });
            observable
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<String>() {
                        @Override
                        public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                        }

                        @Override
                        public void onNext(@io.reactivex.rxjava3.annotations.NonNull String s) {
                            imageUpload(photoFile);
                        }

                        @Override
                        public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });


        }
    }

    void initCamera() {
        LogUtil.e("me", "initCamera->");
        if ((ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_CAMERA);
        } else {
            camera2Helper.openCamera(false);
        }
    }

    void imageUpload(File nFile) {
        showLoading(ResUtils.s(R.string.upload));
        LogUtil.e("me", "URL.uploadUrl->" + U.uploadUrl);
        RxHttp.uploadImage(U.uploadUrl, nFile)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull String s) {
                        if (!TextUtils.isEmpty(s)) {
                            String url = JsonParse.imageUploadJson2Obj(s);
                            LogUtil.e("me", "imageUpload url->" + url);
                            if (!TextUtils.isEmpty(url)) {
                                mUrl = url;
                                showToastDialog(R.mipmap.hit_icon1, ResUtils.s(R.string.upload_completed));
                            }
                        }
                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                        if (e != null) {
                            LogUtil.e("me", "imageUpload e->" + e);
                        }
                        hideLoading();
                        showToastDialog(R.mipmap.hit_icon, ResUtils.s(R.string.upload_failed));
                        mUrl = "";
                    }

                    @Override
                    public void onComplete() {
                        hideLoading();
                    }
                });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        LogUtil.e("me", "requestCode->" + requestCode);
        if (requestCode == MY_PERMISSIONS_CAMERA) {
            initCamera();
        }
    }

}
